package com.example.demo.service;

import com.example.demo.common.TimeTransfer;
import com.example.demo.common.TimerCount;
import com.example.demo.dao.MetaMapper;
import com.example.demo.dao.UserMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.Task;
import com.example.demo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-11-20
 * Time: 19:45
 */
@Slf4j
@Service
public class TaskService {
    @Resource
    private MetaMapper metaMapper;

    @Resource
    private SendMailService sendMailService;

    @Resource
    private UserMapper userMapper;

    /**
     * 创建数据表
     */
    public void createTaskTable() {
        metaMapper.createTaskTable();
    }

    /**
     * 创建用户表
     */
    public void createUserTable() {
        metaMapper.createUserTable();
    }

    /**
     * 根据任务名查询任务
     */
    public Task getTaskByName(String name,Integer userId) {
        return metaMapper.getTaskByName(name,userId);
    }

    /**
     * 添加任务
     */
    public void addTask(Task task) {
        // 2.得到时间数字（精确到分钟）
        String lastTime = task.getDate();
        long deadtime = TimeTransfer.convertTimeToNumber(lastTime);
        long nowtime = TimeTransfer.convertTimeToNumber(System.currentTimeMillis());
        // 3.获取时间差值
        long delay = deadtime - nowtime;
        log.warn("[addTask]需要等待时间为："+delay);
        Date deadLine = new Date(deadtime);;
        if (delay < 0) {
            log.warn("添加失败：name = "+task.getName());
            throw new ApplicationException("添加失败，任务已超时");
        }
        // 获取到用户对象
        UserInfo user = userMapper.getUserById(task.getUserId());
        if (user == null) {
            log.error("[addTask] 查询到用户为空！userid = "+task.getId());
            throw new ApplicationException("用户对象为空");
        }
        // 添加任务到数据库
        metaMapper.addTask(task);
        // 发送邮件的定时任务
        Date sendMailTime = new Date(deadtime-30000);
        TimerCount.timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 加上这个条件判断是为了防止中途被修改
                Task taskByName = metaMapper.getTaskByName(task.getName(), task.getUserId());
                if (taskByName != null && !taskByName.getDeleteState() && taskByName.getIsDone() == 0) {
                    System.out.println("[addTask]"+taskByName);
                    sendMailService.sendMail(user.getEmail(),"任务截止提醒",
                            "您的任务：【"+task.getName()+"】即将截止了，请尽快完成。详情请咨询：http://118.25.26.147:37080/login.html");
                    log.info("提醒邮件已发送：userName = "+user.getUsername()+", taskName = "+task.getName());
                }
            }
        }, sendMailTime);

        // 下面是核心模块（定时操作）
//        Timer timer = new Timer();
        TimerCount.timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 这里是定时结束后需要执行的任务
                // 获取任务ID
                // 更新为超时状态
                Task taskByName = metaMapper.getTaskByName(task.getName(), task.getUserId());
                System.out.println("[addTask]"+taskByName);
                if (taskByName != null && taskByName.getIsDone()==0) {
                    metaMapper.updateTaskByName(task.getName(),task.getUserId());
                    log.warn("[DemoApplication]您的任务已超时 userName = "+user.getUsername()+", taskName = "+task.getName());
                }
            }
        },deadLine);
    }

    /**
     * 查询未完成的任务
     */
    public List<Task> getAllTodoTask() {
        return metaMapper.getAllTodoTask();
    }

    /**
     * 查询已完成的任务
     */
    public List<Task> getAllDoneTask() {
        return metaMapper.getAllDoneTask();
    }

    /**
     * 删除指定任务，根据任务Id
     */
    public void deleteTask(Integer id) {
        metaMapper.deleteTask(id);
    }

    /**
     * 删除指定任务，根据任务名
     */
    public int deleteTaskByName(String name,Integer userId) {
        int row = metaMapper.deleteTaskByName(name,userId);
        if (row != 1) {
            log.error("删除任务失败: name = "+name);
            throw new ApplicationException("删除任务失败!");
        }
        return row;
    }

    /**
     * 更新任务状态，根据任务id
     */
    public int updateTask(Integer id){
        int row = metaMapper.updateTask(id);
        if (row != 1) {
            log.warn("更新失败：id = "+id);
            throw new ApplicationException("更新失败!");
        }
        return row;
    }

    /**
     * 更新任务状态：根据用户名
     * @param name
     * @return
     */
    public int updateTaskByNameP(String name,Integer userId) {
        int row = metaMapper.updateTaskByNameP(name,userId);
        if (row != 1) {
            log.warn("更新失败：name = "+name);
            throw new ApplicationException("更新失败!");
        }
        System.out.println("[updateTaskByNameP]更新成功!");
        return row;
    }

    /**
     * 获取所有的任务
     */
    public List<Task> getAll(Integer userId) {
        return metaMapper.getAll(userId);
    }

}
